<template>
    <div class="container">
        <div class="breadcrumb">
            数据搜索
        </div>
        <div class="mt20"></div>
        <!-- 搜索条件 -->
        <n-form :model="queryState" inline label-placement="left" label-width="auto" autocomplete="off">
            <n-form-item name="type" style="width: 20%;">
                <n-input v-model:value="queryState.index" placeholder="_index" :readonly="route.query.i"></n-input>
            </n-form-item>
            <n-form-item name="keyword" style="width: 60%;">
                <n-input v-model:value="queryState.keyword" placeholder="关键字搜索">
                    <template #suffix>
                        <n-icon class="pointer" :component="SearchOutlined" @click="onQuery" />
                    </template>
                </n-input>
            </n-form-item>
            <n-form-item v-if="result.ms || result.total">
                <span>耗时: {{ result.ms }} 毫秒,结果共:{{ result.total }}条数据</span>
            </n-form-item>
        </n-form>

        <!-- 数据表 -->
        <n-data-table remote pagination-behavior-on-filter="first" :columns="columns" :data="dataSource" striped />

    </div>
</template>

<script setup lang="ts">
import { SearchOutlined } from '@vicons/antd';
import { h, onMounted, reactive } from "vue";
import { useRoute } from 'vue-router';
import { getSearch } from "../../config/api";
import VueJsonPretty from 'vue-json-pretty';
import 'vue-json-pretty/lib/styles.css';

const route = useRoute();

const queryState = reactive({
    index: '',
    keyword: '',
});


onMounted(() => {
    if (route.query.i) {
        queryState.index = route.query.i as string;
        onQuery();
    }
})

const onQuery = () => {
    result.ms = 0;
    result.total = 0;
    dataSource.length = 0;
    getSearch(queryState.index, queryState.keyword).then(res => {
        if (res.data) {
            result.ms = res.data.took;
            result.total = typeof res.data.hits.total === 'object' ? res.data.hits.total.value : res.data.hits.total;
            Object.assign(dataSource, res.data.hits.hits)
        }
    })
}

const result = reactive({
    ms: 0,
    total: 0,
})

let dataSource = reactive([]);

const columns = [
    { title: '_id', key: '_id', sorter: false, width: 200, },
    { title: '_index', key: '_index', sorter: false, width: 80, },
    { title: '_score', key: '_score', sorter: false, width: 80, },
    {
        title: '_source', key: 'data', sorter: false, render(row: any) {
            // return JSON.stringify(row['_source'])
            return h(VueJsonPretty,{data:row['_source']});
        }
    },
];


</script>